package com.work.studio.presenters;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;

import com.ghnor.flora.common.ApplicationLoader;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.work.studio.App;
import com.work.studio.MainActivity;
import com.work.studio.constracts.MainContract;
import com.work.studio.entitys.AttendanceStatisticsEntity;
import com.work.studio.entitys.BaseApiEntity;
import com.work.studio.entitys.CustomerEntity;
import com.work.studio.entitys.CustomerSignEntity;
import com.work.studio.entitys.CustomerVisitRntity;
import com.work.studio.entitys.DailyFinishEntity;
import com.work.studio.entitys.RankingEntity;
import com.work.studio.net.ConsumerMy;
import com.work.studio.net.NetManager;
import com.work.studio.utils.SPUtils;

import java.io.File;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class MainPresenter implements MainContract.Presenter {

    private MainContract.View mView;
    public Disposable mTimePool;//时间
    public Disposable mTodayPool;//考勤统计
    public Disposable mFinishPool;//完成率统计
    public Disposable mVisitorPool;//拜访统计
    public Disposable mRankingPool;//排行榜
    public Disposable mRecyclePool;//排行榜列表
    public Disposable mMapPool;//地图数据展示
    private long initialDelay = 1;
    private long period = 60;
    private String TAG = this.getClass().getSimpleName();
    private RxPermissions rxPermissions;

    public MainPresenter(MainContract.View mView) {
        this.mView = mView;

//        App app = (App) this.mView.getContext().getApplicationContext();
//        period = app.getDataRefreshTimeSecond();
//        period = SPUtils.getInt(this.mView.getContext(), "DataRefreshTimeSecond", 60);
    }


    @Override
    public void initThreadPool(Context context) {

        try {

            //时间轮询
            initThread(initialDelay, 1, 1);
            //今日考勤统计
            initThread(initialDelay, period, 2);
            //昨日日报完成率
            initThread(initialDelay, period, 3);
            //客户拜访次数统计
            initThread(initialDelay, period, 4);
            //客户拜访排行榜
            initThread(initialDelay, period, 5);
            //今日实时拜访客户
            initThread(initialDelay, period, 6);
            //地图人员数据
            initThread(initialDelay, period, 7);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 停止线程
     */
    @Override
    public void stopPool() {

        try {

            canclePool();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 检查线程是否有效
     *
     * @param disposable
     * @return
     */
    private boolean checkThread(Disposable disposable) {

        try {

            if (disposable == null) {

                return true;

            }

            if ((disposable != null && disposable.isDisposed())) {
                disposable = null;
                return true;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 初始化线程
     *
     * @param initialDelay 延迟时间
     * @param period       间隔时间轮询
     * @param type         类型
     */
    private void initThread(long initialDelay, long period, int type) {

        try {

            if (type == 1) {

                if (checkThread(mTimePool)) {
                    mTimePool = Observable.interval(initialDelay, period, TimeUnit.SECONDS)
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Consumer<Long>() {
                                @Override
                                public void accept(Long aLong) throws Exception {

//                                    Log.e(TAG, "时间统计:" + aLong);


                                    if (mView != null) {
                                        mView.onTimePool();
                                    }
                                }
                            });
                }

            } else if (type == 2) {
                if (checkThread(mTodayPool)) {
                    mTodayPool = Observable.interval(initialDelay, period, TimeUnit.SECONDS)
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Consumer<Long>() {
                                @Override
                                public void accept(Long aLong) throws Exception {

//                                    Log.e(TAG, "今日统计:" + aLong);

                                    requestToday();

                                }
                            });
                }
            } else if (type == 3) {
                if (checkThread(mFinishPool)) {
                    mFinishPool = Observable.interval(initialDelay, period, TimeUnit.SECONDS)
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Consumer<Long>() {
                                @Override
                                public void accept(Long aLong) throws Exception {

//                                    Log.e(TAG, "完成率统计:" + aLong);

                                    requestFinish();

                                }
                            });
                }
            } else if (type == 4) {
                if (checkThread(mVisitorPool)) {
                    mVisitorPool = Observable.interval(initialDelay, period, TimeUnit.SECONDS)
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Consumer<Long>() {
                                @Override
                                public void accept(Long aLong) throws Exception {

//                                    Log.e(TAG, "拜访统计:" + aLong);

                                    requestVisitor();


                                }
                            });
                }
            } else if (type == 5) {
                if (checkThread(mRankingPool)) {
                    mRankingPool = Observable.interval(initialDelay, period, TimeUnit.SECONDS)
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Consumer<Long>() {
                                @Override
                                public void accept(Long aLong) throws Exception {

//                                    Log.e(TAG, "排行榜:" + aLong);
                                    requestRanking();
                                }
                            });
                }
            } else if (type == 6) {
                if (checkThread(mRecyclePool)) {
                    mRecyclePool = Observable.interval(initialDelay, period, TimeUnit.SECONDS)
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Consumer<Long>() {
                                @Override
                                public void accept(Long aLong) throws Exception {

//                                    Log.e(TAG, "排行榜:" + aLong);
                                    requestCustomer();
//                                    requestCustomerRecycle();

//                                    if (mView != null) {
//                                        mView.onRecycleViewPool();
//                                    }
                                }
                            });
                }
            } else if (type == 7) {
                if (checkThread(mMapPool)) {
                    mMapPool = Observable.interval(initialDelay, period, TimeUnit.SECONDS)
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Consumer<Long>() {
                                @Override
                                public void accept(Long aLong) throws Exception {

//                                    Log.e(TAG, "地图:" + aLong);

                                    requestMapViewDatas();


                                }
                            });
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取某日客户实时拜访
     */
    private void requestMapViewDatas() {
        try {

            NetManager.getNet()
                    .requestMapViewDatas()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new ConsumerMy<BaseApiEntity<CustomerSignEntity>>() {
                        @Override
                        protected void _onSuccess(BaseApiEntity<CustomerSignEntity> apiEntity) {
                            super._onSuccess(apiEntity);

                            if (mView != null) {

                                if (mView != null) {
                                    CustomerSignEntity customerSignEntities = apiEntity.getContent();
                                    if (customerSignEntities != null) {
                                        mView.onMapViewDatas(customerSignEntities.getCustomerReturnList());
                                    }
                                }
                            }
                        }

                        @Override
                        protected void _onError(String errorCode, String errorMessage) {
                            super._onError(errorCode, errorMessage);
                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取某日客户实时拜访
     */
    private void requestCustomerRecycle() {

        try {

            NetManager.getNet()
                    .requestCustomerRecycle()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new ConsumerMy<BaseApiEntity<CustomerSignEntity>>() {
                        @Override
                        protected void _onSuccess(BaseApiEntity<CustomerSignEntity> apiEntity) {
                            super._onSuccess(apiEntity);

                            if (mView != null) {

                                CustomerSignEntity customerSignEntities = apiEntity.getContent();
                                if (customerSignEntities != null) {
                                    mView.onCustomerRecycle(customerSignEntities.getCustomerReturnList());
                                }
                            }
                        }

                        @Override
                        protected void _onError(String errorCode, String errorMessage) {
                            super._onError(errorCode, errorMessage);
                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void requestCustomer() {

        try {

            NetManager.getNet()
                    .requestCustomer()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new ConsumerMy<BaseApiEntity<CustomerEntity>>() {
                        @Override
                        protected void _onSuccess(BaseApiEntity<CustomerEntity> apiEntity) {
                            super._onSuccess(apiEntity);

                            if (mView != null) {

                                CustomerEntity customerEntity = apiEntity.getContent();
                                if (customerEntity != null) {

                                    if (mView != null) {
                                        mView.onRequestCustomer(customerEntity);
                                    }
                                }
                            }
                        }

                        @Override
                        protected void _onError(String errorCode, String errorMessage) {
                            super._onError(errorCode, errorMessage);
                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取某月份客户拜访客户排行榜
     */
    private void requestRanking() {
        try {

            NetManager.getNet()
                    .requestRanking()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new ConsumerMy<BaseApiEntity<List<RankingEntity>>>() {
                        @Override
                        protected void _onSuccess(BaseApiEntity<List<RankingEntity>> apiEntity) {
                            super._onSuccess(apiEntity);

                            if (mView != null) {

                                if (mView != null) {
                                    List<RankingEntity> rankingEntities = apiEntity.getContent();
                                    mView.onRankingSuccess(rankingEntities);
                                }
                            }
                        }

                        @Override
                        protected void _onError(String errorCode, String errorMessage) {
                            super._onError(errorCode, errorMessage);
                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 客户拜访次数日统计
     */
    private void requestVisitor() {
        try {

            NetManager.getNet()
                    .requestVisitor()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new ConsumerMy<BaseApiEntity<List<CustomerVisitRntity>>>() {
                        @Override
                        protected void _onSuccess(BaseApiEntity<List<CustomerVisitRntity>> apiEntity) {
                            super._onSuccess(apiEntity);

                            if (mView != null) {

                                if (mView != null) {
                                    List<CustomerVisitRntity> customerVisitRntities = apiEntity.getContent();
                                    mView.onCustomerVisitorSuccess(customerVisitRntities);
                                }
                            }
                        }

                        @Override
                        protected void _onError(String errorCode, String errorMessage) {
                            super._onError(errorCode, errorMessage);
                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 销售日报完成率
     */
    private void requestFinish() {

        try {

            NetManager.getNet()
                    .requestFinish()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new ConsumerMy<BaseApiEntity<DailyFinishEntity>>() {
                        @Override
                        protected void _onSuccess(BaseApiEntity<DailyFinishEntity> apiEntity) {
                            super._onSuccess(apiEntity);

                            if (mView != null) {

                                mView.onFinishSuccess(apiEntity.getContent());

                            }
                        }

                        @Override
                        protected void _onError(String errorCode, String errorMessage) {
                            super._onError(errorCode, errorMessage);
                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 考勤缺勤统计
     */
    public void requestToday() {
        try {

            NetManager.getNet()
                    .requestToday()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new ConsumerMy<BaseApiEntity<AttendanceStatisticsEntity>>() {
                        @Override
                        protected void _onSuccess(BaseApiEntity<AttendanceStatisticsEntity> apiEntity) {
                            super._onSuccess(apiEntity);

                            if (mView != null) {
                                AttendanceStatisticsEntity attendanceStatisticsEntity = apiEntity.getContent();
                                if (attendanceStatisticsEntity != null) {
                                    mView.onTodaySuccess(attendanceStatisticsEntity);
                                }
                            }
                        }

                        @Override
                        protected void _onError(String errorCode, String errorMessage) {
                            super._onError(errorCode, errorMessage);
                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void disposePool(Disposable disposable) {
        try {

            if (disposable != null) {

                if (!disposable.isDisposed()) {
                    disposable.dispose();
                }

                disposable = null;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void canclePool() {
        disposePool(mTimePool);
        disposePool(mTodayPool);
        disposePool(mFinishPool);
        disposePool(mVisitorPool);
        disposePool(mRankingPool);
        disposePool(mRecyclePool);
        disposePool(mMapPool);
    }


    /**
     * 检查权限
     */
    public void checkPermission(Context mContext) {


        try {

            if (rxPermissions == null) {
                rxPermissions = new RxPermissions((MainActivity) mContext);
            }

            if (!rxPermissions.isGranted(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                againRequestPermission(mContext, Manifest.permission.READ_EXTERNAL_STORAGE);
                Log.e("", "Manifest.permission.READ_EXTERNAL_STORAGE");
                return;
            }

            if (!rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                againRequestPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                Log.e("", "Manifest.permission.WRITE_EXTERNAL_STORAGE");
                return;
            }

            if (!rxPermissions.isGranted(Manifest.permission.READ_PHONE_STATE)) {
                againRequestPermission(mContext, Manifest.permission.READ_PHONE_STATE);
                Log.e("", "Manifest.permission.READ_PHONE_STATE");
                return;
            }

//            if (!rxPermissions.isGranted(Manifest.permission.INTERNET)) {
//                againRequestPermission(mContext, Manifest.permission.INTERNET);
//                Log.e("", "Manifest.permission.INTERNET");
//                return;
//            }


            mView.permissionSuc();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 再次请求
     *
     * @param permissionStr
     */
    private void againRequestPermission(Context context, String permissionStr) {
        try {

            RxPermissions permissions = new RxPermissions((MainActivity) context);
            permissions.setLogging(true);
            permissions.requestEach(permissionStr)
                    .subscribe(new Consumer<Permission>() {
                        @Override
                        public void accept(Permission permission) throws Exception {
                            //申请和返回的权限名
                            if (permission.granted) {
                                //权限被用户通过
                                checkPermission(context);
                                Log.e("", permission.name + " 申请通过");
                            } else if (permission.shouldShowRequestPermissionRationale) {
                                Log.e("", permission.name + " 申请被拒不再提示");
                                //权限被用户禁止，且选择‘不在提示’，当下次涉及此权限，不会弹出权限申请框
                                //不需要解释为何需要该权限，直接请求授权
                                againRequestPermission(context, permissionStr);
                            } else {
                                Log.e("", permission.name + " 申请被拒再提示");

                                //权限被用户禁止，但未选中‘不在提示’，则下次涉及此权限还会弹出权限申请框
                                //跳转到该应用的设置界面，让用户手动授权
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", context.getPackageName(), null);
                                intent.setData(uri);
                                ((MainActivity) context).startActivityForResult(intent, 1001);
                            }
                        }
                    });

        } catch (Exception e) {
            Log.e("", "" + e.getLocalizedMessage());
        }
    }

    public File getDefaultFileCompressDirectory() {
        File file = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            file = ApplicationLoader.getApplication().getExternalFilesDir(null);
        }
        file = file == null ? ApplicationLoader.getApplication().getFilesDir() : file;

        file = new File(file.getParentFile(), "File-Cache");
        if (!file.exists())
            file.mkdirs();
        return file;
    }


    public void setDataRefreshTimeSecond(int dataRefreshTimeSecond) {

        if (dataRefreshTimeSecond > 0) {
            this.period = dataRefreshTimeSecond*2;
        } else {
            this.period = 60;//默认60s
        }
    }

}
